# -*- coding: utf-8 -*-
"""
Created on 2021/5/31 16:28

@File: create_a_new_customer.py
@Author: LT
@Description: 1.去到名为t_user的数据表查询以获得新建站点的userName和password2，也就是每个站点各自的账号及密码。
              先用len(result)是否大于1，若是的话，则取最后一项，因为最新建的在最后插入。
              2.取到站点的账号密码后，去往节度使前端来进行新增客户(无须使用账号密码登录，直接post就行了)。
              3.记得要把站点名后面加上（客户）二字以此来区分，这样才不会影响数据库以战点名字来搜寻出来的结果。
"""
from requests import post
from ...about_database.query_database import QueryDatabase
import json
import time


# class SearchDatabase:
#     def __init__(self, TARGET_NAME):
#         self.query = QueryDatabase()
#         self.userId = self.query.execute_select('t_user', 'shortName', TARGET_NAME)[-1]['userId']  # 租户的userId
#         self.companyId = self.query.execute_select('t_user', 'shortName', TARGET_NAME)[-1]['companyId']  # 租户的companyId


# class CreateNewCustomer(SearchDatabase):
class CreateNewCustomer:
    def __init__(self,
                 station_name: '场站 名称',
                 address: '具体 地址',
                 province: '省 份',
                 city: '市 区',
                 county: '县 域',
                 regionCode: '县域代码 比如瑞安市应该是330381',
                 streettown: '街道 村镇',
                 longitude: '经 度',
                 latitude: '纬 度',
                 manager: '联系 人',
                 tel: '联系 电话',
                 regisId: '工商注册号 格式为：站点名 + 时间戳',
                 gatewayvender: '网关 厂家',
                 powersupplyarea: '供电 区域',
                 doornumber: '户 号',
                 doorname: '户 名',
                 **kwargs
                 ):
        renter_name = station_name + kwargs.get('renter_suffix')
        customer_name = station_name + kwargs.get('customer_suffix')

        renter_userId = kwargs.get("renter_userId")
        renter_companyId = kwargs.get("renter_companyId")

        # SearchDatabase.__init__(self, renter_name)
        self.create_link = 'https://zhisheng.wzies.com/backend/company/user/inOrUpUser'  # 创建客户的接口
        self.query_link = 'https://zhisheng.wzies.com/backend/company/user/queryUser'  # 查询主库中客户的参数信息接口

        self.headers = {'Content-Type': 'application/json;charset=UTF-8'}  # payload形式必须有请求头表示它是什么类型的，这里用json类型！

        self.create_data = {
            "companyId": renter_companyId,  # 必填，也就是说要从数据库中额外获得companyId，然后工商注册号为空就行，只填一个场站名字就行
            "token": "a6c622bab352459893e517dd608473b5",  # 可以删掉不填它
            "userId": renter_userId,  # 必填，也就是说要从数据库中额外获得userId，然后工商注册号为空就行，只填一个场站名字就行
            "accountId": renter_userId,  # accountId与userId一致
            "from": "front",
            "level": 3,
            "companyName": customer_name,
            "shortName": customer_name,
            "regisId": regisId,
            "contract": manager,
            "contractPhone": tel,
            "provinceCode": "330000",
            "cityCode": "330300",
            "regionCode": regionCode,
            "address": address,
            "industry1": "制造业",
            "industry2": "其他制造业",
            "operation": "add",
            "timestamp": round(time.time()),
            "lang": "zh-CN"
        }

        self.query_data = {
            "companyId": renter_companyId,           # 租户query后的companyId
            "userId": renter_userId,              # 租户query后的userId
            "accountId": renter_userId,           # 租户query后的userId
            "from": "front",
            "level": 3,
            "page": 1,
            "lang": "zh-CN"
        }

        self.res = self.__request()                     # 创建客户的请求结果
        self.params_dict = self.__query_request()       # 查询主库中刚创建好的客户参数的字典结果

    def __request(self):
        res = post(url=self.create_link, data=json.dumps(self.create_data), headers=self.headers)
        res.close()
        return res

    def __query_request(self):
        time.sleep(1)                   # 等待一秒，为了确保刚创建的客户写进了数据库
        res = post(url=self.query_link, data=json.dumps(self.query_data), headers=self.headers)
        res.close()

        dic = {}
        if str(res.json().get('msg')) == 'SUCCESS':
            content = res.json().get("data").get("list")[0]
            dic = dict(
                customer_userId=content.get("userId"),
                customer_companyId=content.get("companyId"),
            )

        return dic
